import store from "@/store/index.js"
import sign from "../util/getSign.js"
// import Storage from "../util/storage.js"

let BASE_URL="XXX"
// #ifdef H5
	// console.log(process.env.NODE_ENV)
	BASE_URL = process.env.NODE_ENV === 'production' ? BASE_URL : "/api"
// #endif
const request = (config) => {
	// 处理 apiUrl
	config.url = BASE_URL + config.url;

	let BASEDATA = {
		"reqid": Math.random().toString(36).substr(2,15),
		// 时间戳，单位：秒
		"timestamp": Date.parse(new Date())/1000,
		// 通过微信获取的用户openid
		// #ifdef H5
		"openid": store.state.userInfo.openid||"nil",
		// #endif
		// #ifndef H5
		"openid": store.state.userInfo.openid||"init",
		// #endif
		// 签名
		// "sign": sign.get_sign({}),
		"qz_gdt":store.state.query.qz_gdt||"",
		// 渠道id		
		"pid": store.state.query.pid||"1",
		"click_id":store.getters.click_id,		//getParams('click_id')
		"from":store.state.query.from||"",		//getParams('from')
		"content_id":store.state.query.content_id||"",
		"adgroup_id":store.state.query.adgroup_id||"",
		"campaign_id":store.state.query.campaign_id||"",
		"t":"h5",
		...config.data
	}
	if(BASEDATA.from=="hudong"){
		BASEDATA.ad_click_url = store.state.query.ad_click_url
	}
	let baseData = sign.sign.get_sign(BASEDATA)
	config.data = baseData
	let promise = new Promise(function(resolve, reject) {
		uni.request(config).then(responses => {
			// 异常
			if (responses[0]) {
				reject({message : "网络超时"});			
			}else{
				let response = responses[1].data; //
				if(response.status==0||response.status==200){
					resolve(response);
				}else{
					uni.showToast({
						icon:"error",
					    title: response.msg,
					    duration: 2000,
						success: () => {
							uni.hideLoading();
						}
					});
					reject({message:response.msg?response.msg:"请求失败！"})
				}					
			}
			
		}).catch(error => {
			console.log("error")
			console.log(error)
			uni.hideLoading()
			reject(error);
			uni.showToast({
			    title: error,
			    duration: 2000
			});
		})
	})
	return promise;
};

export default request;
